package com.thermoberg.zhousi.controller;


import com.thermoberg.zhousi.model.Message;
import com.thermoberg.zhousi.util.LoginToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.sql.Array;
import java.util.HashMap;
import java.util.Map;

/*
  该类的作用主要是用于登录功能
 */
@Controller
public class UserController {

    @Autowired
    private Environment env;

    @Autowired
    LoginToken loginToken;

    @RequestMapping("/toLogin")
    public String toLogin(){
        return "login";
    }

    @RequestMapping(value = "/login",method = RequestMethod.POST)
    @ResponseBody
    public Object login(HttpServletResponse res,String admincode,String password){
        Message message = new Message();

        if(!findUsers().containsKey(admincode)){
            message.setMessage("账号错误,无法登陆!");
            message.setSuccess(0);
            return message;

        }
        if(!findUsers().get(admincode).equals(password)){
            message.setMessage("密码错误,无法登陆!");
            message.setSuccess(1);
            return message;

        }
        //登陆成功后,将账号和密码传入cookie中,以便于判断
        sendCookie(res,admincode,password);
        return message;

    }
    //该方法是用来读取属性文件里面设置的账号和密码
    public Map<String,String>findUsers(){
        Map<String,String>map = new HashMap<String, String>();
        String str = env.getProperty("admin.list");
        //System.out.println(str);
        if(str == null||str.isEmpty()){
            return map;
        }
        String [] users = str.split(";");
        for(int i = 0;i<users.length;i++){
           String admincode = users[i].split(",")[0];
           String password = users[i].split(",")[1];
           map.put(admincode,password);
        }
        return map;
    }
    //将账号和密码加密并绑定到cookie上面,用于后面的判断
   public void sendCookie(HttpServletResponse res,String admincode,String password ){
        String token=loginToken.buildToken(admincode,password);
        res.addCookie(buildCookie("token",token));
    }


    //new一个cookie对象,便于上面调用
    public Cookie buildCookie(String name,String value){
        Cookie cookie = new Cookie(name,value);
        cookie.setMaxAge(60*60*2);
        cookie.setPath("/");
        return cookie;
    }
}
